/**
 * 
 */
package com.stryker.newproject;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.stryker.R;
import com.stryker.model.Project;
import com.stryker.model.User;
import com.stryker.network.CallService;
import com.stryker.ultilities.Application;
import com.stryker.ultilities.Ultilities;

/**
 * @author Admin
 * 
 */
public class ScreenNewProjectActivity extends Activity {

	/** The Constant SOAP_ACTION. */
	private static final String SOAP_ACTION = "http://tempuri.org/M_GetProject";

	/** The Constant METHOD_NAME. */
	private static final String METHOD_NAME = "M_GetProject";

	/** The Constant NAMESPACE. */
	private static final String NAMESPACE = "http://tempuri.org/";

	private List<Project> listProjects;
	private List<Project> listProjectsSearch;
	private Application apps;
	private User user;
	private String minIndex = "0";
	private String maxIndex = "30";
	private String _where = ""; // set search

	private ListView listViewProject;
	private ListViewNewProjectsAdapter m_Adapter;
	private Dialog progressDialog;

	private LinearLayout linearLayoutNodata;
	private EditText txt_search_project;

	/** The update task. */
	private Runnable updateTask;

	/** The gui thread. */
	private Handler guiThread;

	/**
	 * Called when the activity is first created.
	 * 
	 * @param savedInstanceState
	 *            the saved instance state
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// this is code config full screeen
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		Ultilities.mLockScreenRotation(this);
		setContentView(R.layout.screen_new_project);

		linearLayoutNodata = (LinearLayout) findViewById(R.id.linearLayoutNodata);
		txt_search_project = (EditText) findViewById(R.id.txt_search_project);

		listViewProject = (ListView) findViewById(R.id.listViewProject);
		progressDialog = Ultilities.showProgressDialog(this);
		progressDialog.show();

		apps = (Application) getApplication();
		user = apps.getUser();

		String[] params = new String[] { user.getUserType(), "1", minIndex,
				maxIndex, _where, user.getUserID() };

		new GetDataFromWebService().execute(params);

		innitThread();

		txt_search_project.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				queueUpdate(500);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

	}

	// get data from services
	/**
	 * The Class GetDataFromWebService.
	 */
	private class GetDataFromWebService extends AsyncTask<String, Void, String> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected String doInBackground(String... urls) {
			String URL = getResources().getString(R.string.Config_Url_Server);
			CallService callService = new CallService();

			listProjects = callService.getAllNewProjects(SOAP_ACTION,
					METHOD_NAME, NAMESPACE, URL, urls[0], urls[1], urls[2],
					urls[3], urls[4], urls[5]);
			return null;
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(String result) {
			if (listProjects.size() > 0) {
				m_Adapter = new ListViewNewProjectsAdapter(
						ScreenNewProjectActivity.this,
						R.layout.row_new_project, listProjects);
				listViewProject.setAdapter(m_Adapter);
			} else {
				linearLayoutNodata.setVisibility(View.VISIBLE);
			}
			progressDialog.cancel();

		}
	}

	/**
	 * Innit thread.
	 */
	private void innitThread() {
		guiThread = new Handler();
		updateTask = new Runnable() {

			@Override
			public void run() {
				// Mapping textSearch voi 1 EditText object
				// txtSearch nay la cai EditText minh viet ham
				// OnTextChangeListener
				// EditText et = (EditText)findViewById(R.id.txt_city_search);
				// check if null return
				String word = txt_search_project.getText().toString().trim();
				if (word.equalsIgnoreCase("")) {
					// if not change set listView first
					// for (int i = 0; i < listCitys.size(); i++) {
					// items[i] = listCitys.get(i).getCityName();
					// }
					listViewProject.setAdapter(new ListViewNewProjectsAdapter(
							ScreenNewProjectActivity.this,
							R.layout.row_new_project, listProjects));
				} else
				// if txtSearch not null
				{

					// get data from webservice
					getDataByKeywords(word);
					// Show on list
					listProjectsSearch = new ArrayList<Project>();

					// get data from webservice
					listProjectsSearch = getDataByKeywords(word);
					m_Adapter.notifyDataSetChanged();
					listViewProject.setAdapter(new ListViewNewProjectsAdapter(
							ScreenNewProjectActivity.this,
							R.layout.row_new_project, listProjectsSearch));
					m_Adapter.notifyDataSetChanged();

				}

			}
		};
	}

	/**
	 * Queue update.
	 * 
	 * @param delayMillisecond
	 *            the delay millisecond
	 */
	private void queueUpdate(long delayMillisecond) {
		guiThread.removeCallbacks(updateTask);
		// update data if no change in textSearch after time config
		// timer by = milliseconds
		guiThread.postDelayed(updateTask, delayMillisecond);
	}

	public List<Project> getDataByKeywords(String keyword) {
		listProjectsSearch = new ArrayList<Project>();
		keyword = keyword.toUpperCase();
		for (int i = 0; i < listProjects.size(); i++) {
			String contain = listProjects.get(i).getMprtname().toUpperCase();
			if (contain.contains(keyword)) {
				listProjectsSearch.add(listProjects.get(i));
			}
		}
		return listProjectsSearch;
	}

}
